//
//  OAuthViewController.swift
//  HJWeibo
//
//  Created by huangjiong on 16/2/4.
//  Copyright © 2016年 huangjiong. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {
    
    let WbAppKey = "4062258339"
    let WbAppSecret = "4e1545c6129905512659dba94bc83568"
    let WbRedirectUri = "http://www.guqu.net"
    

    override func loadView() {
        super.loadView()
        
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //初始化导航条
        navigationItem.title = "黄炯微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        //获取未授权的RequestToken,即跳转到未登录界面
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(WbAppKey)&redirect_uri=\(WbRedirectUri)"
        let url = NSURL(string: urlStr)
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
    }
    
    //MARK: - 关闭当前登录界面
    func close()
    {
        dismissViewControllerAnimated(true, completion: nil)
    }

    // MARK: - 懒加载一个网页视图
    private lazy var webView = UIWebView()
    
}

extension OAuthViewController:UIWebViewDelegate
{
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //1.先获取到将要跳转的url字符串
        let urlStr = request.URL!.absoluteString
        if urlStr.hasPrefix(WbRedirectUri) == false
        {
            return true
        }
        
        //判断是否授权成功
        let parameterStr = "code="
        if request.URL!.query!.hasPrefix(parameterStr)
        {
            //授权成功
            print("授权成功")
            //取出已经授权的RequestToken
            let code = request.URL!.query?.substringFromIndex(parameterStr.endIndex)
            
            //换取accessToken
            loadAccessToken(code!)
            
        } else
        {
            //取消授权时,关闭
            print("取消成功")
            close()
        }
        
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.showInfoWithStatus("正在加载...", maskType: SVProgressHUDMaskType.Black)
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    private func loadAccessToken(code: String)
    {
        //path路径
        let path = "oauth2/access_token"
        //参数
         let params = ["client_id":WbAppKey, "client_secret":WbAppSecret, "grant_type":"authorization_code", "code":code, "redirect_uri":WbRedirectUri]
        //发送请求
        HJNetworkManager.sharedManager().POST(path, parameters: params, progress: { (_) -> Void in
            
            }, success: { (_, JSON) -> Void in
                
                //建模型
                let account = UserAccount(dict: JSON as! [String: AnyObject])
                
                //网络获取用户信息
                account.loadUserInfo({ (account, error) -> () in
                    
                    if account != nil
                    {
                        //保存
                        account?.saveAccount()
                        
                    } else
                    {
                        SVProgressHUD.showInfoWithStatus("网络不给力...", maskType: SVProgressHUDMaskType.Black)
                    }
                })
                
            }) { (_, error) -> Void in
                
                 SVProgressHUD.showInfoWithStatus("网络不给力...", maskType: SVProgressHUDMaskType.Black)
        }
    
    }
}